import request from './request';
import type { 
  DoctorListParams, 
  PatientSickCircleListParams,
  PatientCircleFormData,
  PatientCircleDetailParams,
  PatientCircleCommentParams,
  PublishCommentParams,
  SickCollectionParams,
  CommentListParams,
  ExpressOpinionParams
} from '../type/store';
import type {
  HealthInfoCollectionItem,
  SickCircleCollectionItem,
  VideoCollectionItem,
  CollectionListParams,
  CollectionListResponse,
  SearchParams,
  SearchResult
} from '../type';

// ==================== 知识库相关API ====================

// 病症相关API
export const diseaseService = {
  // 获取病症分类导航
  getDiseaseCategories: () => 
    request.get('/api/health/share/knowledgeBase/v1/findDepartment'),
  
  // 获取病症列表
  getDiseaseList: (departmentId: number) => 
    request.get(`/api/health/share/knowledgeBase/v1/findDiseaseCategory?departmentId=${departmentId}`),
  
  // 获取病症详情
  getDiseaseDetail: (id: number) => 
    request.get(`/api/health/share/knowledgeBase/v1/findDiseaseKnowledge?id=${id}`)
};

// 药品相关API
export const drugService = {
  // 获取药品分类导航
  getDrugCategories: () => 
    request.get('/api/health/share/knowledgeBase/v1/findDrugsCategoryList'),
  
  // 获取药品列表
  getDrugList: (params: {
    drugsCategoryId: string;
    page: number;
    count: number;
  }) => 
    request.get('/api/health/share/knowledgeBase/v1/findDrugsKnowledgeList', { params }),
  
  // 获取药品详情
  getDrugDetail: (id: number) => 
    request.get(`/api/health/share/knowledgeBase/v1/findDrugsKnowledge?id=${id}`)
};

// ==================== 资讯相关API ====================

export const informationService = {
  // 获取资讯分类
  getInformationCategories: () => 
    request.get('/api/health/share/information/v1/findInformationPlateList'),
  
  // 获取资讯列表
  getInformationList: (params: {
    plateId?: number;
    page: number;
    count: number;
  }) => 
    request.get('/api/health/share/information/v1/findInformationList', { params }),
  
  // 获取资讯详情
  getInformationDetail: (infold: number) => 
    request.get('/api/health/share/information/v1/findInformation', { 
      params: { infold } 
    })
};

// ==================== 首页相关API ====================

export const homeService = {
  // 获取轮播图
  getBannerList: () => 
    request.get('/api/health/share/v1/bannersShow'),
  
  // 获取问诊医生列表
  getConsultationDoctors: (params: DoctorListParams) => 
    request.get('/api/health/share/v1/findDoctorList', { params })
};

// ==================== 搜索相关API ====================

export const searchService = {
  // 首页搜索
  getHomePageSearch: (params: SearchParams) => 
    request.get('/api/health/share/v1/homePageSearch', { params })
};

// ==================== 用户关注相关API ====================

export const userFollowService = {
  // 获取用户关注医生列表
  getUserFollowDoctorList: (params: {
    page: number;
    count: number;
  }) => {
    const config = createAuthRequestConfig(params);
    return request.get('/api/health/user/verify/v1/findUserDoctorFollowList', config);
  },

  // 取消关注医生
  cancelFollowDoctor: (doctorId: number) => {
    const config = createAuthRequestConfig({ doctorId });
    return request.delete('/api/health/user/inquiry/verify/v1/cancelFollow', config);
  }
};

// ==================== 问诊相关API ====================

export const consultationService = {
  // 获取医生详情
  getDoctorDetail: (doctorId: string | number) => 
    request.get('/api/health/user/inquiry/v1/findDoctorInfo', { 
      params: { doctorId } 
    }),
  
  // 获取医生评价列表
  getDoctorEvaluations: (params: {
    doctorId: string | number;
    page: number;
    count: number;
  }) => 
    request.get('/api/health/user/inquiry/v1/findDoctorEvaluateList', { params }),
  
  // 关注医生
  followDoctor: (data: {
    doctorId: string | number;
    userId: number;
    sessionId: string;
  }) => 
    request.post('/api/health/user/inquiry/verify/v1/followDoctor', null, {
      params: { doctorId: data.doctorId },
      headers: {
        userId: data.userId,
        sessionId: data.sessionId
      }
    }),
  
  // 取消关注医生
  cancelFollowDoctor: (data: {
    doctorId: string | number;
    userId: number;
    sessionId: string;
  }) => 
    request.delete('/api/health/user/inquiry/verify/v1/cancelFollow', { 
      params: { doctorId: data.doctorId },
      headers: {
        userId: data.userId,
        sessionId: data.sessionId
      }
    }),
  
  // 预约医生
  bookDoctor: (data: {
    doctorId: string | number;
    appointmentTime: string;
    description?: string;
  }) => 
    request.post('/api/health/user/inquiry/v1/bookAppointment', data),
  
  // 获取预约记录
  getAppointments: (params: {
    page: number;
    count: number;
    status?: string;
  }) => 
    request.get('/api/health/user/inquiry/v1/getAppointments', { params })
};

// ==================== 用户相关API ====================

export const userService = {
  // 用户登录
  login: (data: {
    username: string;
    password: string;
  }) => 
    request.post('/api/user/login', data),
  
  // 用户注册
  register: (data: {
    username: string;
    password: string;
    email?: string;
    phone?: string;
  }) => 
    request.post('/api/user/register', data),
  
  // 获取用户信息
  getUserInfo: () => 
    request.get('/api/user/info'),
  
  // 更新用户信息
  updateUserInfo: (data: any) => 
    request.put('/api/user/info', data),
  
  // 用户登出
  logout: () => 
    request.post('/api/user/logout')
};

// ==================== 病友圈相关API ====================

export const patientCircleService = {
  // 获取科室分类列表
  getKnowledgeBase: () => 
    request.get('/api/health/share/knowledgeBase/v1/findDepartment'),
  
  // 根据科室ID获取病症列表
  getKnowledgeBaseListByID: (departmentId: number) => 
    request.get('/api/health/share/knowledgeBase/v1/findDiseaseCategory', {
      params: { departmentId }
    }),
  
  // 发布病友圈帖子
  publishSickCircle: (data: PatientCircleFormData) => {
    const config = createAuthRequestConfig(undefined, data);
    return request.post('/api/health/user/sickCircle/verify/v1/publishSickCircle', data, {
      headers: config.headers
    });
  },
  
  // 上传病友圈图片
  uploadSickCirclePicture: (sickCircleId: number, picture: File) => {
    const { userId, sessionId } = getUserAuthInfo();
    
    const formData = new FormData();
    formData.append('picture', picture);
    formData.append('sickCircleId', sickCircleId.toString());
    
    return request.post('/api/health/user/sickCircle/verify/v1/uploadSickCirclePicture', formData, {
      headers: {
        userId,
        sessionId,
        'Content-Type': 'multipart/form-data'
      }
    });
  },
  
  // 获取病友圈详情
  getSickCircleDetail: (params: PatientCircleDetailParams) => {
    const config = createAuthRequestConfig(params);
    return request.get('/api/health/user/sickCircle/v1/findSickCircleInfo', config);
  },

  // 获取病友圈评论列表
  getSickCircleCommentList: (params: PatientCircleCommentParams) => {
    const config = createAuthRequestConfig(params);
    return request.get('/api/health/user/sickCircle/v1/findSickCircleCommentList', config);
  },
  
  // 发表评论
  publishComment: (data: PublishCommentParams) => {
    const config = createAuthRequestConfig({
      sickCircleId: data.sickCircleId,
      content: data.content
    });
    return request.post('/api/health/user/sickCircle/verify/v1/publishComment', null, config);
  },

  // 获取病友的发帖列表
  getPatientSickCircleList: (params: PatientSickCircleListParams) => {
    const config = createAuthRequestConfig(params);
    return request.get('/api/health/user/sickCircle/v1/findPatientSickCircleList', config);
  },

  // 收藏病友圈
  postCollection: (data: SickCollectionParams) => {
    const config = createAuthRequestConfig({ sickCircleId: data.sickCircleId });
    return request.post('/api/health/user/verify/v1/addUserSickCollection', null, config);
  },

  // 取消收藏病友圈
  deleteCollection: (params: SickCollectionParams) => {
    const config = createAuthRequestConfig({ sickCircleId: params.sickCircleId });
    return request.delete('/api/health/user/verify/v1/cancelSickCollection', config);
  },

  // 查询病友圈评论列表（新接口）
  getCircleComment: (params: CommentListParams) => {
    const config = createAuthRequestConfig(params);
    return request.get('/api/health/user/sickCircle/v1/findSickCircleCommentList', config);
  },

  // 赞同/反对病友圈评论
  putExpressOpinion: (params: ExpressOpinionParams) => {
    const config = createAuthRequestConfig(params);
    return request.put('/api/health/user/sickCircle/verify/v1/expressOpinion', null, config);
  }
};

// ==================== 视频相关API ====================

export const videoService = {
  // 获取视频列表
  getVideoList: (params: {
    page: number;
    count: number;
    categoryId?: number;
  }) => 
    request.get('/api/health/user/video/v1/findVideoVoList', { params }),

  // 收藏视频
  addVideoCollection: (videoId: number) => {
    const { userId, sessionId } = getUserAuthInfo();
    return request.post('/api/health/user/video/verify/v1/addUserVideoCollection', null, {
      params: { videoId },
      headers: { userId, sessionId }
    });
  },

  // 取消收藏视频
  cancelVideoCollection: (videoId: number) => {
    const { userId, sessionId } = getUserAuthInfo();
    return request.delete('/api/health/user/verify/v1/cancelVideoCollection', {
      params: { videoId },
      headers: { userId, sessionId }
    });
  },

  // 发表视频评论(弹幕)
  addVideoComment: (videoId: number, content: string) => {
    const { userId, sessionId } = getUserAuthInfo();
    return request.post('/api/health/user/video/verify/v1/addVideoComment', null, {
      params: { videoId, content },
      headers: { userId, sessionId }
    });
  }
};

// ==================== 通用API工具函数 ====================

// 获取用户认证信息
const getUserAuthInfo = () => {
  const userInfo = localStorage.getItem('userInfo');
  
  if (!userInfo) {
    throw new Error('用户未登录，请先登录');
  }
  
  try {
    const parsed = JSON.parse(userInfo);
    const userId = parsed.userId?.toString();
    const sessionId = parsed.sessionId;
    
    if (!userId || !sessionId) {
      throw new Error('用户信息不完整，请重新登录');
    }
    
    return { userId, sessionId };
  } catch (error) {
    console.error('解析用户信息失败:', error);
    throw new Error('用户信息解析失败，请重新登录');
  }
};

// 创建需要认证的请求配置
const createAuthRequestConfig = (params?: any, data?: any) => {
  const { userId, sessionId } = getUserAuthInfo();
  
  const config: any = {
    headers: { userId, sessionId }
  };
  
  if (params) {
    config.params = params;
  }
  
  if (data) {
    config.data = data;
  }
  
  return config;
};

// 统一处理API响应
export const handleApiResponse = <T>(response: any): T => {
  return response.data.result || response.data.data || response.data || [];
};

// 统一处理API错误
export const handleApiError = (error: any): string => {
  return error.message || '请求失败，请稍后重试';
};

// ==================== 收藏相关API ====================

export const collectionService = {
  // 获取用户健康资讯收藏列表
  getHealthInfoCollectionList: (params: CollectionListParams) => {
    const config = createAuthRequestConfig(params);
    return request.get('/api/health/user/verify/v1/findUserInfoCollectionList', config);
  },

  // 获取用户病友圈收藏列表
  getSickCircleCollectionList: (params: CollectionListParams) => {
    const config = createAuthRequestConfig(params);
    return request.get('/api/health/user/verify/v1/findUserSickCollectionList', config);
  },

  // 获取用户健康视频收藏列表
  getVideoCollectionList: (params: CollectionListParams) => {
    const config = createAuthRequestConfig(params);
    return request.get('/api/health/user/verify/v1/findVideoCollectionList', config);
  },

  // 收藏健康资讯
  addInfoCollection: (infold: number) => {
    const config = createAuthRequestConfig({ infold });
    return request.post('/api/health/user/verify/v1/addUserInfoCollection', null, config);
  },

  // 取消收藏健康资讯
  cancelInfoCollection: (infold: number) => {
    const config = createAuthRequestConfig({ infold });
    return request.delete('/api/health/user/verify/v1/cancelInfoCollection', config);
  }
};

// ==================== 导出所有服务 ====================

export default {
  diseaseService,
  drugService,
  informationService,
  homeService,
  searchService,
  userFollowService,
  consultationService,
  userService,
  patientCircleService,
  videoService,
  collectionService,
  handleApiResponse,
  handleApiError
};
